package com.zhongshengnetwork.rightbe.lang.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
//import com.bumptech.glide.load.resource.drawable.GlideDrawable;
//import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.AppUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.Filter.FilterTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.imageviewer.ImageLoader;
import com.zhongshengnetwork.rightbe.imageviewer.ImageViewerState;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.listener.OnItemClickListener;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;

import org.xutils.common.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

//import cn.jiguang.analytics.android.api.JAnalyticsInterface;

import static com.just.agentweb.BaseJsAccessEntrace.TAG;
import static com.zhongshengnetwork.rightbe.MainActivity.REQUEST_PERMISSION;

public class SelfImagePreviewActivity extends Activity {

    private List<ViewData> mViewDatas = null;
    private List<Object> mImageList = null;
    private String imgs = null;
    private int viewX = 0;
    private int viewY = 0;
    private int imgW = 0;
    private int imgH = 0;
    private int position = 0;
    private int number = 3;
    private boolean isListImg = false;
    private static boolean isFinish = false;
    private ImageViewer imagePreivew;
    //加载动画
    private AVLoadingIndicatorView avi;

    private int filterIndex = 0;

    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (AppUtils.getInstance().getAppStatus() == AppUtils.STATUS_FORCE_KILLED){
            //app被系统回收了，重新启动应用
            protectApp();
            return;
        }
        overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.
        isFinish = false;
        setContentView(R.layout.activity_self_image_preview);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        avi.show();
        imagePreivew = (ImageViewer) findViewById(R.id.imageVivewer);
        imagePreivew.doDrag(false);
        imagePreivew.doEnterAnim(true);
        imagePreivew.doExitAnim(true);
        imagePreivew.setDuration(400);
        Log.e("TAG","最大放大系数="+imagePreivew.getImageMaxScale());
        position = getIntent().getIntExtra("position",0);
        isListImg = getIntent().getBooleanExtra("isListImg",false);
        imgs = getIntent().getStringExtra("imgs");
        viewX = getIntent().getIntExtra("viewX",0);
        viewY = getIntent().getIntExtra("viewY",0);
        imgW = getIntent().getIntExtra("imgW",0);
        imgH = getIntent().getIntExtra("imgH",0);
        number = getIntent().getIntExtra("number",3);
        filterIndex = getIntent().getIntExtra("filterIndex", 0);
        if (!CommonUtils.isEmpty(imgs)){
            List<String> list = CommonUtils.stringToArrayList(imgs);
            if (list != null && list.size() > 0){
                mViewDatas = new ArrayList<ViewData>();
                mImageList = new ArrayList<Object>();
                int firstX = viewX;
                int firstY = viewY;
                if (isListImg == true){
                    firstX = viewX-imgW*(position%number);
                    firstY = viewY-imgH*(position/number);
                }
                for (int i = 0; i < list.size(); i++){
                    /*
                    if (list.get(i).contains(Constant.weijuTakePhoto) == true){
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),list.get(i)));
                        mImageList.add(imageUri.getPath());
                    }else {
                        mImageList.add(list.get(i));
                    }
                    */
                    mImageList.add(list.get(i));
                    ViewData viewData = new ViewData();
                    viewData.setTargetHeight(imgH);
                    viewData.setTargetWidth(imgW);
                    if (isListImg == true){
                        viewData.setTargetX(firstX+imgW*(i%number));
                        viewData.setTargetY(firstY+imgH*(i/number));
                    }else {
                        viewData.setTargetX(firstX);
                        viewData.setTargetY(firstY);
                    }
                    mViewDatas.add(viewData);
                }
                // 图片浏览的起始位置
                imagePreivew.setStartPosition(position);
                imagePreivew.setImageData(mImageList);
                // 外部 View 的位置以及尺寸等信息
                imagePreivew.setViewData(mViewDatas);
                imagePreivew.setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(int position, Object source, final ImageView imageView) {

                        Glide.with(SelfImagePreviewActivity.this).load(source).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).centerCrop().dontAnimate().into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                avi.hide();
                                if (filterIndex > 0){
                                    BitmapDrawable bd = (BitmapDrawable) resource;
                                    if (bd != null){
                                        Bitmap bitmap = bd.getBitmap();
                                        imageView.setImageBitmap(FilterTools.toProcessImage(bitmap, filterIndex));
                                    }else {
                                        imageView.setImageDrawable(resource);
                                    }

                                }else {
                                    imageView.setImageDrawable(resource);
                                }
                            }
                        });
                    }
                });
                imagePreivew.watch();
                imagePreivew.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public boolean onItemClick(int position, View view) {
                        if(SelfImagePreviewActivity.this != null && imagePreivew.mAttacher != null && !imagePreivew.mAttacher.isImageAnimRunning()){
                            if (imagePreivew.mAttacher.getViewState() == ImageViewerState.STATE_WATCHING){
                                if (isFinish == false){
                                    isFinish = true;
                                    imagePreivew.setClickable(false);
                                    imagePreivew.setImageScaleable(false);
                                    imagePreivew.close();
                                    new Handler().postDelayed(new Runnable(){
                                        public void run() {
                                            //execute the task
                                            finish();
                                            overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.
                                            CustomApplication.isWatchingImg = false;
                                        }
                                    }, 300);
                                }
                            }
                        }
                        return true;
                    }
                });
                imagePreivew.setOnItemLongClickListener(new com.zhongshengnetwork.rightbe.imageviewer.listener.OnItemLongClickListener() {
                    @Override
                    public void onItemLongClick(int position, View view) {
                        Log.e("TAG","长按了图片："+position);
                        showSaveImage(position);
                    }
                });

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
    return;
}
//JAnalyticsInterface.onPageStart(getApplicationContext(),this.getClass().getCanonicalName());
    }


    @Override
    protected void onPause() {
        super.onPause();
        if(AppUtils.getInstance().isUserAgreeStatus() == false){
    return;
}
//JAnalyticsInterface.onPageEnd(getApplicationContext(),this.getClass().getCanonicalName());
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean b = imagePreivew.onKeyDown(keyCode, event);
        if (b) {
            if (isFinish == false){
                isFinish = true;
                imagePreivew.setClickable(false);
                imagePreivew.setImageScaleable(false);
                new Handler().postDelayed(new Runnable(){
                    public void run() {
                        //execute the task
                        finish();
                        overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.
                        CustomApplication.isWatchingImg = false;
                    }
                }, 300);
            }
            return b;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showSaveImage(final int position){
        PermissionUtils.isPictureNote(SelfImagePreviewActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(SelfImagePreviewActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(SelfImagePreviewActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    REQUEST_PERMISSION);
                            return;
                        }
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(SelfImagePreviewActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(SelfImagePreviewActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(SelfImagePreviewActivity.this,"亲，请开启应用对SD卡的读写权限");
                        return;
                    }

                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(SelfImagePreviewActivity.this)
                            .builder()
                            .setTitle("请选择")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    actionSheetDialog.addSheetItem("保存图片", null, new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            download((String) mImageList.get(position));

                        }
                    });
                    actionSheetDialog.show();
                }
            }
        });
    }

    protected void protectApp() {
//        Intent intent = new Intent(this, MainActivity.class);
//        intent.putExtra(AppUtils.KEY_HOME_ACTION, AppUtils.ACTION_RESTART_APP);
//        startActivity(intent);

        Intent intent = new Intent(this, SplashActivity.class);
        startActivity(intent);
        System.exit(0);
        finish();

//        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);

        //杀掉以前进程
        //android.os.Process.killProcess(android.os.Process.myPid());
    }

    // 保存图片到手机
    public void download(final String url) {

        new AsyncTask<Void, Integer, File>() {

            @Override
            protected File doInBackground(Void... params) {
                File file = null;
                try {
                    FutureTarget<File> future = Glide
                            .with(SelfImagePreviewActivity.this)
                            .load(url)
                            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

                    file = future.get();

                    // 首先保存图片
                    File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();

                    File appDir = new File(pictureFolder ,"WeiJu");
                    if (!appDir.exists()) {
                        appDir.mkdirs();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";
                    File destFile = new File(appDir, fileName);

                    FileUtil.copy(file.getPath(), destFile.getPath());

                    // 最后通知图库更新
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(new File(destFile.getPath()))));


                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
                return file;
            }

            @Override
            protected void onPostExecute(File file) {

                Toast.makeText(SelfImagePreviewActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }
        }.execute();
    }
}

